package br.edu.ufcg.embedded.eolica.view;

import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.TimeZone;

import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.StringItem;

import com.sun.cldc.util.j2me.CalendarImpl;

import br.edu.ufcg.embedded.eolica.MIDlet.UsinaEolicaMIDlet;
import br.edu.ufcg.embedded.eolica.domain.User;
import br.edu.ufcg.embedded.eolica.exception.FacadeException;
import br.edu.ufcg.embedded.eolica.facade.Facade;
import br.edu.ufcg.embedded.eolica.util.Properties;

public class ConsultFormAtt extends Form implements CommandListener, ItemStateListener {

	private Display d;
	private Displayable previous;
	private Command cmdConsult, cmdBack;
	private Facade facade;
	private ChoiceGroup graphTypeChoice, heightChoice, periodChoice;
	private User user;
	private Properties prop;
	private GraphForm g;
	private Hashtable graphProperties;
	private String[] heightOptions, periodOptions;	
	private String station;
	private String graphType;
	private DateField dateFieldInit, dateFieldEnd;
	private boolean dateFieldOn;
	private int dateFieldInitIndex, dateFieldEndIndex;
	
	public ConsultFormAtt(Display d, Displayable previous, String title) {
		super("Eletrobras - " + title);
		this.d = d;
		this.previous = previous;
		
		graphProperties = new Hashtable();
		facade = Facade.getInstance();
		
		try {
			this.user = facade.getUser();
		} catch (FacadeException e) {
			d.setCurrent(new ErrorAlert(prop.getProperty("label.error"), prop.getProperty("error.userload")), previous);
		}
		
		loadComponents();
		graphType = GraphForm.WIND_GRAPH;
	}

	private void loadComponents() {
		prop = UsinaEolicaMIDlet.getProp();
		
		String windInfo = prop.getProperty("label.windspeed");
		String probabilisticBehavior = prop.getProperty("label.statisticalspeed");
		
		graphProperties.put(prop.getProperty(windInfo), GraphForm.WIND_GRAPH);
		graphProperties.put(prop.getProperty(probabilisticBehavior), GraphForm.STATISTICAL_GRAPH);
		graphProperties.put(prop.getProperty("label.height1"), new Integer(12));
		graphProperties.put(prop.getProperty("label.height2"), new Integer(70));
		graphProperties.put(prop.getProperty("label.height3"), new Integer(100));
		graphProperties.put(prop.getProperty("label.height4"), new Integer(102));
		graphProperties.put(prop.getProperty("label.period1"), new Integer(1));
		graphProperties.put(prop.getProperty("label.period2"), new Integer(7));
		graphProperties.put(prop.getProperty("label.period3"), new Integer(15));
		graphProperties.put(prop.getProperty("label.period4"), new Integer(60));
		graphProperties.put(prop.getProperty("label.period5"), new Integer(180));
		
		heightOptions = new String[]{prop.getProperty("label.height1"), prop.getProperty("label.height2"), prop.getProperty("label.height3"), prop.getProperty("label.height4")};
		periodOptions = new String[]{prop.getProperty("label.period1"), prop.getProperty("label.period2"), prop.getProperty("label.period3")};
		heightChoice = new ChoiceGroup(prop.getProperty("label.height"), Choice.EXCLUSIVE, heightOptions, null);
		periodChoice = new ChoiceGroup(prop.getProperty("label.period"), Choice.EXCLUSIVE, periodOptions, null);
		periodChoice.append(prop.getProperty("label.newdatespec"), null);
		graphTypeChoice = new ChoiceGroup(prop.getProperty("label.graphlisttype"), Choice.EXCLUSIVE, new String[]{windInfo, probabilisticBehavior}, null);
		
		dateFieldInit = new DateField("Date Init", DateField.DATE);
		dateFieldEnd = new DateField("Date End", DateField.DATE);
		
		cmdConsult = new Command(prop.getProperty("label.consult"), Command.OK, 0);
		cmdBack = new Command(prop.getProperty("label.back"), Command.BACK, 0);
		
		append(graphTypeChoice);
		append(heightChoice);
		append(periodChoice);
		addCommand(cmdConsult);
		addCommand(cmdBack);
		setCommandListener(this);		
		setItemStateListener(this);
	}
	
	public void setSelectedStation(String station) {
		this.station = station;
	}

	public void commandAction(Command cmd, Displayable arg1) {
		if(cmd == cmdBack)
			d.setCurrent(previous);
		
		else if(cmd == cmdConsult) {
			if(g == null)
				g = new GraphForm(d, this, prop.getProperty("label.graph"));
			
			String heightName = heightChoice.getString(heightChoice.getSelectedIndex());
			int height = ((Integer)graphProperties.get(heightName)).intValue();
			
			Date today = new Date();
			Date initDate = null;
			Date finalDate = today;
			
			//if the selected period belongs to the available period list
			Object periodObj = graphProperties.get(periodChoice.getString(periodChoice.getSelectedIndex()));
			if (periodObj != null) {
				int period = ((Integer)periodObj).intValue();            
		        long t = today.getTime();
		        //subtract the desired number of days to the long value using milliseconds per day * number of days
		        final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
		        t += (-1)*period * MILLIS_PER_DAY;
		        initDate = new Date(t);
			} else { //defines new period based on manually date selection
				initDate = dateFieldInit.getDate();
				if(dateFieldEnd.getDate() != null)
					finalDate = dateFieldEnd.getDate();
			}
			
			//d.setCurrent(new ErrorAlert(prop.getProperty("label.error"), prop.getProperty("label.errordate")), this);
			if(initDate == null) //if finalDate not set when asking for set dates manually, consider finalDate == today
				d.setCurrent(new ErrorAlert(prop.getProperty("label.error"), prop.getProperty("label.errordate")), this);
			else {
				long initDateTime = initDate.getTime();
				long finalDateTime = finalDate.getTime();
				long todayTime = today.getTime();
				
				if(initDateTime <= finalDateTime && initDateTime <= todayTime && finalDateTime <= todayTime) {
					g.getGraph(user, station, height, initDateTime, finalDateTime, graphType);
					d.setCurrent(g);
				} else
					//TODO prop.getProperty("error.userload")
					d.setCurrent(new ErrorAlert(prop.getProperty("label.error"), prop.getProperty("error.period")), this);	
			}
			
		}
	}

	public void itemStateChanged(Item item) {
		if(item == graphTypeChoice) {
			String graphName = graphTypeChoice.getString(graphTypeChoice.getSelectedIndex());

			if (graphProperties.get(graphName).equals(GraphForm.WIND_GRAPH)) {
				graphType = GraphForm.WIND_GRAPH;
				periodChoice.set(0, prop.getProperty("label.period1"), null);
				periodChoice.set(1, prop.getProperty("label.period2"), null);
				periodChoice.set(2, prop.getProperty("label.period3"), null);
			} else {
				graphType = GraphForm.STATISTICAL_GRAPH;
				periodChoice.set(0, prop.getProperty("label.period3"), null);
				periodChoice.set(1, prop.getProperty("label.period4"), null);
				periodChoice.set(2, prop.getProperty("label.period5"), null);
			}	
		} else if(item == periodChoice) {
			if(periodChoice.getSelectedIndex() == 3) {
				dateFieldInitIndex = append(dateFieldInit);
				dateFieldEndIndex = append(dateFieldEnd);
				dateFieldOn = true;
			} else {
				if(dateFieldOn) {
					delete(dateFieldEndIndex);
					delete(dateFieldInitIndex);
					dateFieldOn = false;
				}
			}
		}
	}


}
